package com.edu.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.edu.bean.Cars;
import com.edu.service.CarService;
import com.edu.service.NewsService;
import com.edu.service.impl.CarsServiceImpl;
import com.edu.service.impl.NewsServiceImpl;
@WebServlet("/updatecars.do")
@MultipartConfig
public class UpdateCarsServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		CarService cs = new CarsServiceImpl();
		String id = req.getParameter("carid");
		String carname = req.getParameter("carname");
		String carprice = req.getParameter("carprice");
		String saleState = req.getParameter("saleState");
		String introduce = req.getParameter("introduce");
		String type = req.getParameter("type");
		String brand = req.getParameter("brand");
		int carid = Integer.parseInt(id);
		double price = Double.parseDouble(carprice);
		int salstate = Integer.parseInt(saleState);
		Cars car = new Cars(carid,carname,price,salstate,introduce,type,brand);
		//获取用户上传的文件
		Part part = req.getPart("carcover");
		//用户只能上传小于1M的图片，且必须上传
		boolean carcover=false;
		String savePath="";
		if(part.getSize() > 0 ) {
			if(part.getSize() <=1024*1024 || part.getContentType().contains("image")) {
				//生成一个独一无二的文件名.UUID，用户名_时间戳_原始文件名
				String saveName = carname+"_"+System.currentTimeMillis()+part.getSubmittedFileName();
				//把文件存储到服务器的headImg路径下（真实路径）
				savePath = "c:/PhaetonCommunityImg/favoriteCar/"+saveName;
				//访问路径存在数据库，取出来之后直接拼字img下面的src的路径下
				String visitPath = "/PhaetonCommunity/favoriteCar/"+saveName;
				//用户上传的文件需要复制到真实保存路径
				part.write(savePath);
				car.setCarimg(visitPath);
				carcover=true;
			}else {
				req.setAttribute("carsImgMsg","图片必须小于1m");
				return;
			}
		}
		int res = cs.update(car);
		if(res == 1 && carcover) {
			String oldCover=req.getParameter("oldcarsCover");
			if(!"/PhaetonCommunity/favoriteCar/mrtp.jpg".equals(oldCover)) {
				String[] strs=oldCover.split("/");
				String fileName=strs[strs.length-1];
				System.out.println(fileName);
				File file=new File("C:/PhaetonCommunityImg/favoriteCar/"+fileName);
				if(file.exists()) {
					file.delete();
				}
			}
		}
	}
}
